package com.pitop.base.interceptor;

import com.opensso.sdk.client.SessionEnum;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.tools.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * LoginInterceptor
 */
@Component
@Slf4j
public class SupportLoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtils redisUtils;

    /**
     * 登录拦截器，拦截token的合法性
     * 1.获取token
     * 2.验证在缓存中是否存在
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader(SessionEnum.Authorization.name());
        if (StringUtils.isBlank(token)) {
            throw new BaseException(BaseException.BaseExceptionEnum.Session_Error);
        } else {
            //2.验证在缓存中是否存在
            Object object = redisUtils.get(token);
            if(object != null) {
                return  true;
            } else {
                throw new BaseException(BaseException.BaseExceptionEnum.Session_Error);
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}